package algorithm.sort;

import java.util.Arrays;

//归并排序
public class MergetSort {
    public static void main(String[] args) {
        int[] data = new int[]{5, 3, -1, 6, 9, 7, 5, -999, 90, -9};
        mergeSort(data, 0, data.length - 1, new int[data.length]);
        System.out.println(Arrays.toString(data));
    }


    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {  // 表示子序列中有2个或者2个以上的元素
            int mid = (left + right) / 2; //中间索引
            //向左递归进行分解
            mergeSort(arr, left, mid, temp);
            //向右递归进行分解
            mergeSort(arr, mid + 1, right, temp);
            //合并
            merge(arr, left, mid, right, temp);

        }
    }


    //合并
    public static void merge(int[] data, int left, int mid, int right, int[] temp) {

        int i = left;  //左边有序序列的初始索引
        int j = mid + 1;   //右边有序序列的初始索引
        int t = 0;  //temp数组的下标
        while (i <= mid && j <= right) {
            if (data[i] < data[j]) {
                temp[t] = data[i];
                t++;
                i++;
            } else {
                temp[t] = data[j];
                t++;
                j++;
            }
        }
        //将剩余的放入临时数组
        while (i <= mid) {
            temp[t] = data[i];
            t++;
            i++;
        }
        while (j <= right) {
            temp[t] = data[j];
            t++;
            j++;
        }

        //将temp数组里面的数拷贝到原数组中，必须用左右指针，因为temp数组开大了，
        t = 0;
//        int tempLeft = left; //
        while (left <= right) {
            data[left] = temp[t];
            t++;
            left++;
        }
    }
}
